#include "qbinaryrpc_clientprivate.h"

using namespace qbinaryrpc;

Client::Private::Private() : id(0), port(0) {
  connect(&socket, 
          SIGNAL(error(QAbstractSocket::SocketError)),
          this,
          SLOT(error(QAbstractSocket::SocketError)));
  connect(&socket,
          SIGNAL(readyRead()),
          this,
          SLOT(decodeResponse()));
}

void Client::Private::error(QAbstractSocket::SocketError) {
  if(socket.state() == QTcpSocket::ConnectedState) {
    socket.close();
    socket.disconnectFromHost();
  }
  foreach(int id_request, requests) {
    emit fault(id_request, 0, socket.errorString());
  }
  requests.clear();
}

void Client::Private::decodeResponse() {
  QByteArray massive(socket.readAll());
  Response response;
  int now_position(0);
  if(response.setContent(massive, now_position)) {
    if(response.isFault()) {
      emit fault(response.getId(),
                 response.getFaultCode(),
                 response.getFaultString());
    } else {
      emit done(response.getId(), response.getReturnValue());
    }
  } else {
    foreach(int id_request, requests) {
      emit fault(id_request, 2, "Parsing error RPC response");
    }
    requests.clear();
  }
}
